package com.cea.papyrus.diagram.classdiagram.editpart;

import java.util.Iterator;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.ChangeBoundsRequest;

import com.cea.papyrus.core.commands.GraphNodeSetConstraintCommand;
import com.cea.papyrus.core.editpart.DimensionAdaptationEditPolicy;
import com.cea.papyrus.core.figures.IAbstractElementFigure;

public class DimensionAdaptationClassEditPolicy extends DimensionAdaptationEditPolicy {

	public DimensionAdaptationClassEditPolicy() {
		
	}

	protected Command getAdaptDimensionCommand(){
		IFigure fig=getGraphNodeEditPart().getFigure();
		Dimension dim= getGraphNode().getSize();
		
		if (fig instanceof IAbstractElementFigure){
			dim=((IAbstractElementFigure)fig).getMinimumDimension();
		}
		//lok for childEditpart
		Iterator itEditpart=getGraphNodeEditPart().getChildren().iterator();
		while(itEditpart.hasNext()){
			//look for operation or attribute or reception
			Iterator itFeatureIterator= ((EditPart)itEditpart.next()).getChildren().iterator();
			dim.height+=10;
			while(itFeatureIterator.hasNext()){
				GraphicalEditPart currentFeature= (GraphicalEditPart)itFeatureIterator.next();
				fig=currentFeature.getFigure();
				if (fig instanceof IAbstractElementFigure){
					Dimension tempdim=((IAbstractElementFigure)fig).getMinimumDimension();
					dim.height+=tempdim.height;
					if(tempdim.width>dim.width){
						dim.width=tempdim.width;
					}
				}
			}
		}

		Rectangle newBounds= new Rectangle(getGraphNode().getPosition().x,
				getGraphNode().getPosition().y,
				dim.width,
				dim.height);
		ChangeBoundsRequest request= new ChangeBoundsRequest (RequestConstants.REQ_RESIZE);
		Command c =new GraphNodeSetConstraintCommand(getGraphNode(), request,  newBounds);
		return c;
	}

}
